local redis = require("resty.redis")  

local sd = ngx.shared.shared_data
local pool = sd:get('pool')
if pool == nil then
	ngx.log(ngx.ERR,'nil global pool')
	pool = {count=0, next=nil}
	sd:set('pool', pool)
end

if sd:get('pool') == nil then
	ngx.log(ngx.ERR,'set pool not works')
end

-- basic type
if sd:get('foo') == nil then
	sd:set('foo',1)
else
	sd:incr('foo',1)
end
ngx.log(ngx.ERR, 'global foo' .. sd:get('foo'))

-- table
if sd:get('bar') == nil then
	sd:set('bar',{count=1})
end
if sd:get('bar') == nil then
	ngx.log(ngx.ERR, 'set global bar not works')
end



local ip = "127.0.0.1"  
local port = 6379
-- create a new redis connection
local function new_redis_conn()
	ngx.log(ngx.ERR,'new_redis_conn')
	local red = redis:new()
	local ok, err = red:connect(ip, port)
	if not ok then  
	    ngx.log(ngx.ERR,'redis fail to connect')
		close_redis(red)
		return nil
	end
	return red
end

local function recycle_redis_conn(red)
	ngx.log(ngx.ERR,'recycle_redis_conn')
	red:set_timeout(1000000)

	local last = pool
	while last.next ~= nil do
		last = last.next
	end
	last.next = {red = red, next = nil}
	pool.count = pool.count + 1
end

local function get_redis_conn()
	ngx.log(ngx.ERR,'get_redis_conn')
	-- get the first
	if pool.count ==0 then
		ngx.log(ngx.ERR,'empty pool')
		local red = new_redis_conn()
		return red
	end

	local red = pool.next.red
	pool = pool.next.next
	pool.count = pool.count - 1
	return red
end

local red = get_redis_conn()
  


--调用API进行处理  
red:init_pipeline()  
red:set("msg1", "hello1")  
red:set("msg2", "hello2")  
red:get("msg1")  
red:get("msg2")  
local respTable, err = red:commit_pipeline()  
  
--得到的数据为空处理  
if respTable == ngx.null then  
    respTable = {}  --比如默认值  
end  
  
--结果是按照执行顺序返回的一个table  
for i, v in ipairs(respTable) do  
   ngx.say("msg : ", v, "<br/>")  
end  

recycle_redis_conn(red)  